package utils;

import java.io.*;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Logger;

public class FileUtils {
    public final static Charset ENCODING = StandardCharsets.UTF_8;
    public final static String FILE_EXTENSION =".txt";

    public static String readTextFileLine(String fileName)  {
        Path path = Paths.get(fileName);
        try {
            BufferedReader reader = Files.newBufferedReader(path, ENCODING);
            return reader.readLine();
//            while ((line = reader.readLine()) != null) { }
        } catch (IOException ex) {
            System.out.println("Blad wczytywania pliku. Plik pominięty: " + fileName);
            return "";
        }
    }

    public static List<String> readTextFile(String fileName)  {
        Path path = Paths.get(fileName);
        List<String> listWords = new ArrayList<>();
        try {
            BufferedReader reader = Files.newBufferedReader(path, ENCODING);
            //return reader.readLine();
            String line;
            while ((line = reader.readLine()) != null) {
                listWords.add(line);
            }
        } catch (IOException ex) {
            System.out.println("Blad wczytywania pliku. Plik pominięty: " + fileName);
            return null;
        }
        return listWords;
    }

    public static void appendToFile(String txt) {
        try {
            PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter("wyniki.txt", true)));
            out.println(txt);
            out.close();
        } catch (IOException e) {
            //exception handling left as an exercise for the reader
        }
    }

    public static void saveArrayToFile(int[] tab, String pathToSave, String fileName) {
        FileWriter fileWriter = null;
        try {
            File newTextFile = new File(pathToSave + fileName + FILE_EXTENSION);
            fileWriter = new FileWriter(newTextFile);
            fileWriter.write(toDelimitedString(tab, " "));
            fileWriter.close();
        } catch (IOException ex) {
            Logger.getLogger("IOException" + ex);
        } finally {
            try {
                assert fileWriter != null;
                fileWriter.close();
            } catch (IOException ex) {
                Logger.getLogger("IOException" + ex);
            }
        }
    }

    private static String toDelimitedString(int[] ids, String delimiter) {
        StringBuilder strb = new StringBuilder();
        for (int id : ids) {
            strb.append(String.valueOf(id)).append(delimiter);
        }
        return strb.substring(0, strb.length() - delimiter.length());
    }
}
